package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.sse.dto.SseMessageDto;
import org.dromara.common.sse.utils.SseMessageUtils;
import org.dromara.system.domain.SysUserState;
import org.dromara.system.domain.bo.SysUserStateBo;
import org.dromara.system.domain.vo.SysUserStateVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.mapper.SysUserStateMapper;
import org.dromara.system.service.ISysUserService;
import org.dromara.system.service.ISysUserStateService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 用户状态信息Service业务层处理
 *
 * @author Lion Li
 * @date 2025-02-24
 */
@RequiredArgsConstructor
@Service("sysUserStateServiceImpl")
public class SysUserStateServiceImpl implements ISysUserStateService {

    private final SysUserStateMapper baseMapper;
    private final ISysUserService userService;
    private final ScheduledExecutorService scheduledExecutorService;

    /**
     * 查询用户状态信息
     *
     * @param id 主键
     * @return 用户状态信息
     */
    @Override
    public SysUserStateVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询用户状态信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 用户状态信息分页列表
     */
    @Override
    public TableDataInfo<SysUserStateVo> queryPageList(SysUserStateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysUserState> lqw = buildQueryWrapper(bo);
        Page<SysUserStateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的用户状态信息列表
     *
     * @param bo 查询条件
     * @return 用户状态信息列表
     */
    @Override
    public List<SysUserStateVo> queryList(SysUserStateBo bo) {
        LambdaQueryWrapper<SysUserState> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SysUserState> buildQueryWrapper(SysUserStateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysUserState> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SysUserState::getId);
        lqw.like(StringUtils.isNotBlank(bo.getName()), SysUserState::getName, bo.getName());
        lqw.eq(bo.getAvatar() != null, SysUserState::getAvatar, bo.getAvatar());
        return lqw;
    }

    /**
     * 新增用户状态信息
     *
     * @param bo 用户状态信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SysUserStateBo bo) {
        SysUserState add = MapstructUtils.convert(bo, SysUserState.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户状态信息
     *
     * @param bo 用户状态信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SysUserStateBo bo) {
        SysUserState update = MapstructUtils.convert(bo, SysUserState.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean changeStatus(SysUserStateBo bo) {
        SysUserVo userVo = userService.selectUserById(bo.getUserId());
        if (userVo == null) {
            throw new ServiceException("当前用户不存在！");
        }
        // 状态未发生改变，则不改动
        if (bo.getId().equals(userVo.getStateId())) {
            return true;
        }
        // 更新用户状态
        userService.updateUserState(userVo.getUserId(), bo.getId());
        this.baseMapper.updateById(MapstructUtils.convert(bo, SysUserState.class));

        // TODO推送消息
        scheduledExecutorService.schedule(() -> {
            SseMessageDto dto = new SseMessageDto();
            dto.setMessage("更新用户状态");
            dto.setUserIds(List.of(userVo.getUserId()));
            SseMessageUtils.publishMessage(dto);
        }, 1, TimeUnit.SECONDS);
        return true;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysUserState entity) {
        // TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除用户状态信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
